/**
 * SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
 * SPDX-License-Identifier: Mulan PSL v2
 */
<template>
    <div class="table-data">
        <sf-grid>
            <sf-toolbar ref="toolbar">
                <sf-button
                    ref="submit"
                    class="creat-button btn-blank"
                    icon-cls="iconxinzeng2"
                    default-disabled
                    @click="_addInteractTask">
                    <lang>新增任务</lang>
                </sf-button>
                <sf-button
                    ref="submit"
                    class="creat-button btn-blank"
                    icon-cls="iconrefresh"
                    @click="_refresh">
                    <lang>刷新</lang>
                </sf-button>
                <sf-searchfield v-model="searchParams.keyword"
                                class="pull-right"
                                :placeholder="_('请输入任务名称')"
                                @clear="onEnterkey"
                                @trigger="onEnterkey" />
                <sf-select v-model="flowName"
                           :default-width="177"
                           class="pull-right m-r25"
                           :allow-search="true"
                           :allow-blank="true"
                           display-field="aiFlowName"
                           value-field="flowName"
                           :placeholder="_('请选择AI Flow名称')"
                           :options="flowList" />
            </sf-toolbar>
            <sf-table
                ref="updateTimeTable"
                :options="options_fix"
                @pagechange="_onPageChange"
                @sizechange="_onSizeChange">
                <sf-table-column :default-width="20"
                                 type="index">
                    <lang>序号</lang>
                </sf-table-column>
                <sf-table-column data-index="createTime"
                                 :default-width="40">
                    <lang>开始时间</lang>
                </sf-table-column>
                <sf-table-column data-index="name"
                                 :default-width="40">
                    <lang>任务名称</lang>
                </sf-table-column>
                <sf-table-column data-index="flowName"
                                 :default-width="30">
                    <lang>AI FLOW</lang>
                </sf-table-column>
                <sf-table-column data-index="status"
                                 :default-width="30">
                    <lang>状态</lang>
                </sf-table-column>
                <sf-table-column data-index="description"
                                 :default-width="30">
                    <lang>描述</lang>
                </sf-table-column>
                <sf-table-column data-index="parameters"
                                 :default-width="50">
                    <lang>参数</lang>
                </sf-table-column>
                <sf-table-column data-index="metrics"
                                 :default-width="60">
                    <lang>指标</lang>
                </sf-table-column>
                <sf-table-column data-index="opr"
                                 :default-width="80">
                    <lang>操作</lang>
                </sf-table-column>
                <template slot="createTime"
                          slot-scope="{record}">
                    {{ encodeTime(record.createTime) }}
                </template>
                <template slot="flowName"
                          slot-scope="{record}">
                    <!-- 如果AI flow是删除的场景 -->
                    <div :class="!!record.isFlowDeleted?'line-through':''">
                        {{ record.flowName }}
                    </div>
                </template>
                <template slot="status"
                          slot-scope="{record}">
                    <div class="task-flex"
                         :class="repositoryStatusClass(record.status)">
                        <span class="status-img task-common"></span>
                        <span class="status-text">{{ repositoryStatusText(record.status) }}</span>
                    </div>
                </template>
                <template slot="parameters"
                          slot-scope="{record}">
                    <div v-if="!record.parameters">
                        -
                    </div>
                    <div v-else>
                        <div v-for="(item,index) in record.parameters.slice(0,2)"
                             :key="index"
                             :title="translateParams(item.name,item.value)"
                             class="m-tb5">
                            {{ item.name }} : <span class="font-weight">{{ item.value }}</span>
                        </div>
                    </div>
                </template>
                <template slot="metrics"
                          slot-scope="{record}">
                    <div v-if="!record.metrics">
                        -
                    </div>
                    <div v-else
                         class="metrics-flex">
                        <div v-for="(item,index) in record.metrics"
                             :key="index"
                             :title="translateParams(item.name,item.number_value)"
                             class="metrics-name">
                            {{ item.name }} : <span class="font-weight">{{ item.number_value }}</span>
                        </div>
                    </div>
                </template>
                <template slot="createTime"
                          slot-scope="{record}">
                    {{ encodeTime(record.createTime) }}
                </template>
                <template slot="opr"
                          slot-scope="{record}">
                    <div class="opr">
                        <a
                            class="link-btn"
                            @click="_enterTaskDetail(record)">
                            <lang>查看详情</lang>
                        </a>
                        <a
                            class="link-btn"
                            :class="{'disabled': !record.flowName}"
                            @click="_cloneInteractTask(record)">
                            <lang>克隆任务</lang>
                        </a>
                        <a
                            class="link-btn"
                            @click="_deleteInteractTask(record)">
                            <lang>删除</lang>
                        </a>
                    </div>
                </template>
            </sf-table>
        </sf-grid>
    </div>
</template>
<script>
import {
    encodeDate
} from 'src/util/format';

// import parseJson from 'src/util/parse_json.ts';
import store from 'src/vuex/store';
let userID = store.state.userId;
import trainingUrlAdapter from 'src/home/mod_common/training_url_adapter';

// import { deepClone } from 'src/util/deep_clone';
import IntervalTask from 'src/util/interval_task';
import AddInteractTask from 'src/home/mod_cluster/project_manager/components/label_form/add_interact_task.vue';
import { setStorage } from 'src/util/local_storage';


/* 训练状态 */
const PAGE_COUNT = 10;

const REPOSITORY_STATUS_TEXT = {
    0:_('任务完成'),
    1:_('任务中'),
    2:_('任务失败'),
    3:_('任务异常'),
    4:_('任务终止'),
    5:_('任务创建中')
};
const REPOSITORY_STATUS_CLASS = {
    0:'task-success',
    1:'task-run',
    2:'task-fail',
    3:'task-fail',
    4:'task-fail',
    5:'task-run'
};

export default {
    name: 'SingerUpdateTable',
    components:{
    },
    data () {
        return {
            gridOptions: {
                rowCls (record) {
                    return !record.isGroup ? 'is-child-row' : '';
                },
                data: []
            },
            searchParams: {
                keyword: '',
                pageSize: PAGE_COUNT,
                pageNum: 0,
                flowName:''
            },
            defaultWidth:200,
            intervalTask:null,
            showEmptytraining:false,
            emptyText:_('没有找到对应的模型'),
            options_fix: {
                bufferView: false,

                // 配置这个后才可以实现保持勾选状态
                idProperty: 'id',
                selectionHide: true,
                autoHeight:true,
                pagination: {
                    activePage: 1,
                    pageSize: PAGE_COUNT,
                    pageSizes: [Number('10'), Number('20'), Number('50')],
                    layout: [ 'pager', 'sizes', 'jumper']
                }
            },
            flowList:[],
            flowName:''
        };
    },
    computed: {
        projectId () {
            return this.$route.query.projectId || '';
        }
    },
    watch:{
        flowName () {
            this.refreshGrid();
        }
    },
    mounted () {
        this.refreshGrid();
        this.getAIFlowList();
    },
    methods: {

        // 新增任务弹窗
        _createInteractTaskFormWin () {
            if (!this.interactTaskFormWin) {
                this.interactTaskFormWin = this.$modal(AddInteractTask, {
                    autoDestory: true
                });
            }

            return this.interactTaskFormWin;
        },

        // 新增任务
        _addInteractTask () {
            let formWin = this._createInteractTaskFormWin();
            formWin.open({
                reset: true,
                title: _('新增任务'),
                data:{
                    flowList:this.flowList.slice(1, this.flowList.length),
                    flowId:this.flowList[0].aiFlowId,
                    typeList:[{
                        type:0,
                        name:_('单次训练')
                    }],
                    type:0
                },
                buttons: [{
                    cls: 'sfv-btn-primary',
                    actionName: 'submit',
                    loading: true,
                    text:  _('确定')
                }, {
                    cls: 'sfv-btn-primary',
                    actionName: 'copy',
                    text:_('修改当前参数继续新增')
                }, {
                    actionName: 'cancel',
                    text: '取消'
                }],
                copy: () => {
                    let ajaxParams = formWin.formRoot.getJsonValue();
                    this.ajaxSubmitInteractTask(ajaxParams, formWin, 'copy');
                },
                submit: () => {
                    let ajaxParams = formWin.formRoot.getJsonValue();
                    this.ajaxSubmitInteractTask(ajaxParams, formWin);
                }
            });
        },
        _cloneInteractTask (record) {
            let formWin = this._createInteractTaskFormWin();
            this.interactTaskFormWin.formRoot.setJsonValue(record);
            formWin.open({
                title: _('克隆任务'),
                data:{
                    paramList:record.parameters,
                    flowId:record.interactiveFlowId,
                    showAIFlowList:false,
                    typeList:[{
                        type:0,
                        name:_('单次训练')
                    }],
                    type:0
                },
                buttons: [{
                    cls: 'sfv-btn-primary',
                    actionName: 'submit',
                    loading: true,
                    text:  _('确定')
                }, {
                    cls: 'sfv-btn-primary',
                    actionName: 'copy',
                    text:_('修改当前参数继续新增')
                }, {
                    actionName: 'cancel',
                    text: '取消'
                }],
                copy: () => {
                    let ajaxParams = formWin.formRoot.getJsonValue();
                    delete ajaxParams.createTime;
                    this.ajaxSubmitInteractTask(ajaxParams, formWin, 'copy');
                },
                submit: () => {
                    let ajaxParams = formWin.formRoot.getJsonValue();
                    delete ajaxParams.createTime;
                    this.ajaxSubmitInteractTask(ajaxParams, formWin);
                }
            });
        },
        async ajaxSubmitInteractTask (params, formWin, type = 'add') {
            formWin.$mask();
            const ADD_INTERACT_TASK_URL = trainingUrlAdapter(`user/${userID}/interactiveTask`);
            let jsonData = await this.$ajax.post(ADD_INTERACT_TASK_URL, params);
            formWin.$unmask();
            let { success, msg } = jsonData;
            if (!success) {
                return this.$showErr(msg || _('保存失败'));
            }
            if (type === 'add') {
                this.$ok(_('新增任务成功'));
                formWin.hide();
            } else {
                this.$ok(_('克隆任务成功'));
            }
            this.refreshGrid();
        },

             // 刷新grid
        async getAIFlowList () {
            this.$mask();
            const GET_FLOW_LIST_URL = trainingUrlAdapter(`project/${this.projectId}/allInteractiveFlow`);
            let jsonData = await this.$ajax.get(GET_FLOW_LIST_URL, this.searchParams);
            this.$unmask();
            let { success, msg, data } = jsonData;
            if (!success) {
                this.$showErr(msg || _('加载数据失败'));
                return;
            }
            let allAIFlow = {
                aiFlowId: '',
                flowName:'',
                aiFlowName:_('全部AI Flow')
            };
            let list = data;
            for (let i = 0; i < data.length; i++) {
                list[i].aiFlowName = data[i].flowName;
            }
            this.flowList = list;

            // 要考虑到全部AI FLOW场景
            this.flowList.unshift(allAIFlow);
        },
        _createIntervalTask () {
            let vm = this;
            this.intervalTask = new IntervalTask({
                fn: () => {
                     vm.refreshGrid().then(() => {
                        vm.intervalTask && vm.intervalTask.next();
                    });
                },
                interval: 10000,
                autoStart: true
            });
        },
        onEnterkey () {
            this.refreshGrid();
        },
        repositoryStatusClass (status) {
            return REPOSITORY_STATUS_CLASS[status];
        },
        repositoryStatusText (status) {
            return REPOSITORY_STATUS_TEXT[status];
        },

        // 刷新grid
        async refreshGrid () {
            this.searchParams.flowName = this.flowName;
            this.$mask();
            const TRAINING_GET_URL = trainingUrlAdapter(`project/${this.projectId}/interactiveTask/run`);
            this.$unmask();
            let jsonData = await this.$ajax.get(TRAINING_GET_URL, this.searchParams);
            let table = this.$refs.updateTimeTable;
            let {success, msg, data} = jsonData;
            if (!success) {
                this.$showErr(msg || _('加载数据失败'));
                table.loadData([]);
                return;
            }
            if (!table) {
                return;
            }
            this.showEmptytraining = data.list.length === 0;
            table.loadData(data.list || []);
            table.getPagination().setTotal(data.total);
        },

        encodeTime (time) {
            return encodeDate(time);
        },
        async ajaxDeleteInteractTask (record) {
            const DELETE_URL = trainingUrlAdapter(`interactiveTask/${record.id}`);
            this.$mask();
            let jsonData = await this.$ajax.delete(DELETE_URL);
            this.$unmask();
            let {success, msg} = jsonData;
            if (!success) {
                this.$showErr(msg || _('加载数据失败'));
                return;
            }
            this.$ok(_('删除成功'));
            this.refreshGrid();
        },
        _deleteInteractTask (record) {
            this.$confirm({
                title: _('提示'),
                subTitle: _('确定要删除{0}任务吗？', record.name),
                msg: _('删除后，操作无法撤回，请谨慎操作！'),
                icon: 'warning',
                autoClose: true,
                callback: actionName => {
                    if (actionName === 'submit') {
                        this.ajaxDeleteInteractTask(record);
                    }
                }
            });
        },
        _onPageChange (pageNum) {
            Object.assign(this.searchParams, {
                pageNum: pageNum - 1
            });
            this.refreshGrid();
        },
        _onSizeChange (nowPageIndex, nowPageSize) {
            Object.assign(this.searchParams, {
                pageNum: nowPageIndex - 1,
                pageSize: nowPageSize
            });
            this.refreshGrid();
        },
        _refresh () {
            this.refreshGrid();
        },
        translateParams (name, value) {
            return `${name} : ${value}`;
        },
        _enterTaskDetail (item) {
            setStorage('taskInfo', JSON.stringify(item));

             // 跳到周期任务
            setStorage('interactType', 0);
            this.$router.push({
                path: `/project_manager/interact_task_detail`,
                query: Object.assign(this.$route.query, {taskName:item.name})
            });
        }
    },
    beforeDestroy () {
        if (this.intervalTask) {
            this.intervalTask.stop();
            this.intervalTask = null;
        }
    }
};
</script>
<style lang="less">
    .metrics-flex{
        display: flex;
        flex-wrap: wrap;
        .metrics-name{
            margin: 5px 10px;
        }
    }
</style>
